const { Recipe, User } = require('../models');
const { Op } = require('sequelize');
const sequelize = require('sequelize');

// 计算BMR（基础代谢率）
function calculateBMR(weight, height, age, gender) {
  if (gender === 'male') {
    return 66 + (13.7 * weight) + (5 * height) - (6.8 * age);
  } else {
    return 655 + (9.6 * weight) + (1.8 * height) - (4.7 * age);
  }
}

// 根据BMI推荐食谱类型
function getRecommendationsByBMI(bmi) {
  if (bmi < 18.5) {
    return {
      type: '增重',
      caloriesRange: { min: 2500, max: 3000 },
      proteinRatio: 0.3,
      carbsRatio: 0.5,
      fatRatio: 0.2
    };
  } else if (bmi >= 25) {
    return {
      type: '减重',
      caloriesRange: { min: 1500, max: 2000 },
      proteinRatio: 0.4,
      carbsRatio: 0.3,
      fatRatio: 0.3
    };
  } else {
    return {
      type: '保持',
      caloriesRange: { min: 2000, max: 2500 },
      proteinRatio: 0.3,
      carbsRatio: 0.4,
      fatRatio: 0.3
    };
  }
}

async function getRecommendedRecipes(userId) {
  try {
    // 获取用户信息
    const user = await User.findByPk(userId);
    if (!user) {
      throw new Error('用户不存在');
    }

    // 计算BMI
    const heightInMeters = user.height / 100;
    const bmi = user.weight / (heightInMeters * heightInMeters);

    // 计算BMR
    const bmr = calculateBMR(user.weight, user.height, user.age, user.gender);

    // 获取推荐方案
    const recommendation = getRecommendationsByBMI(bmi);

    // 获取早餐推荐
    let breakfast = await Recipe.findAll({
      where: {
        category: '早餐'
      },
      order: [
        [sequelize.literal('ABS(nutrition->>\'$.calories\' - ' + (recommendation.caloriesRange.min * 0.3) + ')'), 'ASC']
      ],
      limit: 2
    });

    // 如果没有找到早餐，获取任意食谱
    if (breakfast.length === 0) {
      breakfast = await Recipe.findAll({
        limit: 2,
        order: sequelize.literal('RAND()')
      });
    }

    // 获取午餐推荐
    let lunch = await Recipe.findAll({
      where: {
        category: '午餐'
      },
      order: [
        [sequelize.literal('ABS(nutrition->>\'$.calories\' - ' + (recommendation.caloriesRange.min * 0.4) + ')'), 'ASC']
      ],
      limit: 2
    });

    // 如果没有找到午餐，获取任意食谱
    if (lunch.length === 0) {
      lunch = await Recipe.findAll({
        limit: 2,
        order: sequelize.literal('RAND()')
      });
    }

    // 获取晚餐推荐
    let dinner = await Recipe.findAll({
      where: {
        category: '晚餐'
      },
      order: [
        [sequelize.literal('ABS(nutrition->>\'$.calories\' - ' + (recommendation.caloriesRange.min * 0.3) + ')'), 'ASC']
      ],
      limit: 2
    });

    // 如果没有找到晚餐，获取任意食谱
    if (dinner.length === 0) {
      dinner = await Recipe.findAll({
        limit: 2,
        order: sequelize.literal('RAND()')
      });
    }

    return {
      userStats: {
        bmi: bmi.toFixed(1),
        bmr: Math.round(bmr),
        recommendationType: recommendation.type,
        dailyCalories: Math.round((recommendation.caloriesRange.min + recommendation.caloriesRange.max) / 2)
      },
      recipes: {
        breakfast,
        lunch,
        dinner
      }
    };
  } catch (error) {
    console.error('获取推荐食谱失败:', error);
    throw error;
  }
}

module.exports = {
  getRecommendedRecipes
}; 